#include <PerformanceTimer.h>

// Timer类实现
Timer::Timer(const std::string& name)
    : name(name), count(0), total_duration(0),
      min_duration(std::numeric_limits<double>::max()),
      max_duration(std::numeric_limits<double>::min()) {}

void Timer::start() {
    start_time = std::chrono::high_resolution_clock::now();
}

void Timer::end() {
    auto end_time = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> duration = end_time - start_time;
    double time_taken = duration.count();

    count++;
    total_duration += time_taken;
    if (time_taken < min_duration) {
        min_duration = time_taken;
    }
    if (time_taken > max_duration) {
        max_duration = time_taken;
    }
}

void Timer::printSummary() const {
    std::cout << "Timer Name: " << name << std::endl;
    std::cout << "Count: " << count << std::endl;
    std::cout << "Min: " << min_duration * 1000 << " ms" << std::endl;
    std::cout << "Max: " << max_duration  * 1000 << " ms" << std::endl;
    std::cout << "Avg: " << getAvgDuration()  * 1000 << " ms" << std::endl;
}

std::string Timer::getName() const {
    return name;
}

int Timer::getCount() const {
    return count;
}

double Timer::getMinDuration() const {
    return min_duration;
}

double Timer::getMaxDuration() const {
    return max_duration;
}

double Timer::getAvgDuration() const {
    return count > 0 ? total_duration / count : 0.0;
}

// TimerManager类实现
TimerManager& TimerManager::getInstance() {
    static TimerManager instance;
    return instance;
}

void TimerManager::start(const std::string& name) {
    if (timers.find(name) == timers.end()) {
        timers[name] = std::make_shared<Timer>(name);
    }
    timers[name]->start();
}

void TimerManager::end(const std::string& name) {
    if (timers.find(name) != timers.end()) {
        timers[name]->end();
    }
}

void TimerManager::printAllSummaries() const {
    for (const auto& timer_pair : timers) {
        timer_pair.second->printSummary();
        std::cout << "--------------------" << std::endl;
    }
}

std::shared_ptr<Timer> TimerManager::getOrCreateTimer(const std::string& name) {
    auto& timer = timers[name];
    if (!timer) {
        timer = std::make_shared<Timer>(name);
    }
    return timer;
}

